package com.onlineClass.edu.service.impl;

import com.onlineClass.edu.constant.LocalCacheKeyConstants;
import com.onlineClass.edu.entity.EduUser;
import com.onlineClass.edu.entity.requestDto.RegisterReqDTO;
import com.onlineClass.edu.mapper.EduUserMapper;
import com.onlineClass.edu.service.IEduUserService;
import com.onlineClass.edu.service.IRegisterService;
import com.onlineClass.edu.utils.MD5Utils;
import com.onlineClass.edu.utils.SaltUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Objects;

/**
 * @author 邓辉
 * @ClassName RegisterServiceImpl
 * @date 2024-05-02 14:19
 */
@Service
@Slf4j
public class RegisterServiceImpl implements IRegisterService {
    @Autowired
    private IEduUserService iEduUserService;
    @Autowired
    private EduUserMapper eduUserMapper;
    @Override
    @Transactional//开启事务
    public Boolean register(RegisterReqDTO registerReqDTO) {
        /**
         *
         1.验证码参数 ===》doublecheck
         2.判重 ==》根据名称从db查找到用户信息
         3.加密注册 ==> 在db里插入一条用户数据
          */
        String userName = registerReqDTO.getUserName();
        if (StringUtils.isEmpty(userName)){
            log.error("[用户名为空]");
            return Boolean.FALSE;
        }
        String password = registerReqDTO.getPassword();
        if (StringUtils.isEmpty(password)){
            log.error("[密码为空]");
            return Boolean.FALSE;
        }
        EduUser eduUser = iEduUserService.findByUserNameEduUser(userName);
        if (!Objects.isNull(eduUser)){
            log.error("[用户已经注册过了]");
            return Boolean.FALSE;
        }
        String salt = SaltUtils.getSalt();
        String newPassword = MD5Utils.md5(password + salt);
        EduUser eduUser1 = new EduUser();
        eduUser1.setUserName(userName);
        eduUser1.setPassword(newPassword);
        eduUser1.setUserSalt(salt);
        //insert插入操作是否成功
        return eduUserMapper.insert(eduUser1) > LocalCacheKeyConstants.DB_INSERT_RESULT_BIGZERO;
    }
}
